import Vue from 'vue'
import VueRouter from 'vue-router'
import {message} from "@/element/message";
import Home from '@/pages/home/Home'
import Detail from '@/pages/detail/Detail'
import Register from '@/pages/login/Register'
import Login from '@/pages/login/Login'
import User from '@/pages/user/Index'
import Publish from '@/pages/publish/Publish'
import Article from "@/pages/article/Article";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: Detail
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/user',
    name: 'User',
    meta: true,
    component: User
  },
  {
    path: '/publish/:id?',
    name: 'Publish',
    meta: true,
    component: Publish
  },
  {
    path: '/article/:id',
    name: 'Article',
    component: Article
  }
]

const router = new VueRouter({
  // mode: 'history',
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  if (to.meta === true) {
    if (localStorage.getItem('user')) {
      next()
    } else {
      message('请先登录', 'warning')
      next({
        path: '/login'
        // query: {redirect: to.fullPath}//将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  } else {
    next()
  }
})

export default router
